package com.kova.api.token;

import com.kova.api.utils.JwtUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * rest api 身份验证
 * Created by kingboyrang on 2025/10/20.
 */
@Aspect
@Component
public class AccessTokenAspect {

    @Before("@annotation(com.kova.api.token.AccessToken)")
    public void  doAccessCheck(JoinPoint point) throws IllegalAccessException, NoSuchMethodException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //获取调用类
        Class clazz = point.getTarget().getClass();

        //获取方法名称
        String methodName = point.getSignature().getName();
        MethodSignature signature = (MethodSignature) point.getSignature();

        //获取调用方法对象
        Class[] parameterTypes = signature.getMethod().getParameterTypes();
        Method method = clazz.getMethod(methodName, parameterTypes);

        //获取注解类对象
        Annotation annotation = method.getAnnotation(AccessToken.class);
        if (annotation == null) {
            //不需要验证
            return;
        }
        AccessToken nrs = (AccessToken) annotation;
        /************************************ 接口方法token验证 start***********************************************/
        if (nrs.required()){
            //用户token
            String token=request.getHeader("token");
            JwtUtils.verifyToken(token);
        }
        /************************************ 接口方法token验证 end***********************************************/

    }
}
